package com.guigusuqi.commonutils.aop;

import com.alibaba.fastjson.JSON;
import com.guigusuqi.commonutils.annotation.LogAnnotation;
import com.guigusuqi.commonutils.utils.HttpContextUtils;
import com.guigusuqi.commonutils.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class LogAspect
{
    //  切点就是该注解，这个注解加在哪里，哪里就是切点
    @Pointcut("@annotation(com.guigusuqi.commonutils.annotation.LogAnnotation)")
    public void pt(){}

    //  环绕通知
    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable
    {
        long beginTime = System.currentTimeMillis();

        //执行方法
        Object result = joinPoint.proceed();

        //执行时常
        Long time = System.currentTimeMillis() - beginTime;

        //保存在日志里
        recordLog(joinPoint, time);
        return result;
    }

    public void recordLog(ProceedingJoinPoint joinPoint, long time)
    {
        //通过连接点可以获得MethodSignature，以及对应切点方法的详情(方法名、参数)
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获得该切点方法
        Method method = signature.getMethod();
        //通过该方法获得该注解详情
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("=====================log start================================");
        log.info("module:{}", logAnnotation.module());
        log.info("operation:{}", logAnnotation.operator());

        //  请求的类名以及方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method:{}", className + "." + methodName + "()");

        //  请求的参数
        Object[] args = joinPoint.getArgs();
        StringBuilder params = new StringBuilder();
        if(ObjectUtils.isNotEmpty(args))
        {
            for (int i = 0; i < args.length; i++)
            {
                params.append("参数").append(i+1).append(":");
                params.append(JSON.toJSONString(args[i]));
                params.append(" ");
            }

        }
        log.info("params:{}", params);

        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        log.info("ip:{}", IPUtils.getIpAddr(request));


        log.info("execute time : {} s", time);
        log.info("=====================log end================================");
    }
}
